AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 77673096
Accepted
比尔盖子
比尔盖子
Asked: 2023-12-17 10:02:06 +0800 CST2023-12-17 10:02:06 +0800 CST 2023-12-17 10:02:06 +0800 CST

您可以使用花括号初始化列表作为(默认)模板参数吗?

  • 772

我需要定义一个接受多个 3D 坐标作为参数的 C++ 模板。当这些坐标的所有维度都定义为单独的整数变量时,参数列表将变得非常长 - 3 个坐标需要 9 个参数,这使得模板难以使用。

因此,非常希望以使用编译时数组的方式声明模板。它们的默认参数也应该直接在模板声明的位置声明为值,而不是变量名。

经过一些实验,令我惊讶的是,我发现 GCC 13 将接受以下 C++ 程序std=c++20:

#include <cstdio>
#include <array>

template <
    std::array<int, 3> offset = {0, 0, 0}
>
struct Array
{
    void operator() (int i, int j, int k) 
    {
        printf("(%d, %d, %d)\n", i + offset[0], j + offset[1], k + offset[2]);
    }
};

int main(void)
{
    Array arr_default;
    arr_default(0, 0, 0);

    Array<{1, 1, 1}> arr;
    arr(0, 0, 0);

    return 0;
}

然而,clang 18 拒绝使用braced-init-list,因为它无效:

test2.cpp:5:30: error: expected expression
    5 |         std::array<int, 3> offset = {0, 0, 0}
      |                                     ^
test2.cpp:17:8: error: no viable constructor or deduction guide for deduction of template arguments of 'Array'
   17 |         Array arr_default;
      |               ^
test2.cpp:7:8: note: candidate template ignored: couldn't infer template argument 'offset'
    7 | struct Array
      |        ^
test2.cpp:7:8: note: candidate function template not viable: requires 1 argument, but 0 were provided
    7 | struct Array
      |        ^~~~~
test2.cpp:20:8: error: expected expression
   20 |         Array<{1, 1, 1}> arr;
      |               ^
3 errors generated.

问题

  1. 它真的是合法的C++程序吗?如果是,我应该使用什么语法来说服 clang 接受它?如果不是,我是否应该报告 GCC 错误以毫无疑问地接受它?

  2. 是否有替代且更兼容的方式来实现我的目标?std::array不必使用,任何其他具有同等效果的方法也可以。

c++
  • 2 2 个回答
  • 338 Views

2 个回答

  • Voted
  1. Best Answer
    user12002570
    2023-12-17T11:26:38+08:002023-12-17T11:26:38+08:00

    问题

    这是CWG 2450和/或CWG 2049,尽管当前语法不允许这样做,但由于下述原因建议允许/有效。这意味着,Gcc 只是抢先允许语法。来自 CWG 2450:

    由于非类型模板参数现在可以具有类类型,因此允许花括号初始化列表作为模板参数似乎是有意义的,但语法不允许这样做。

    (强调我的)

    如果您想知道当前语法如何不允许这样做,来自temp.name#1:

    template-argument:
        constant-expression
        type-id
        id-expression 
    

    并且由于不是上面列出的三个构造中的任何一个,因此根据当前语法{1, 1, 1}规则,它不能用作模板参数。


    是否有替代且更兼容的方式来实现我的目标?

    解决方案

    您可以在花括号初始化列表之前显式编写,std::array如下所示:

    #include <cstdio>
    #include <array>
    
    template <
    //------------------------------vvvvvvvvvv----------->added this
        std::array<int, 3> offset = std::array{0, 0, 0}
    >
    struct Array
    {
        void operator() (int i, int j, int k) 
        {
            printf("(%d, %d, %d)\n", i + offset[0], j + offset[1], k + offset[2]);
        }
    };
    
    int main(void)
    {
        Array arr_default;
        arr_default(0, 0, 0);
    //--------vvvvvvvvvv------------------->added this
        Array<std::array{1, 1, 1}> arr;
        arr(0, 0, 0);
    
        return 0;
    }
    

    笔记

    另请注意,clang trunk也开始接受该程序,而 gcc 和 msvc 已经从早期版本接受了该程序。

    • 11
  2. Pepijn Kramer
    2023-12-17T12:48:52+08:002023-12-17T12:48:52+08:00

    在当前的 C++ 中,我希望你的代码看起来像这样:

    #include <iostream>
    #include <format>
    #include <vector>
    
    // using namespace std; <== unlearn to use this (risk of nameclashes in big projects)
    
    // this is how you declare a structure/class template
    template<typename type_t> 
    struct vector_3d_t
    {
        type_t x;
        type_t y;
        type_t z;
    };
    
    // make new strong types (don't use `using` for this)
    struct position_3d_t : public vector_3d_t<int> {};
    struct velocity_3d_t : public vector_3d_t<int> {};
    
    position_3d_t update(const position_3d_t& position, const velocity_3d_t& velocity)
    {
        return position_3d_t 
        { 
            position.x + velocity.x,
            position.y + velocity.y,
            position.z + velocity.z 
        };
    }
    
    // Overload operator<< so ostreams (like std::cout) know
    // how to format one vector_3d_t
    template <typename type_t>
    std::ostream& operator<<(std::ostream& os, const vector_3d_t<type_t>& vector)
    {
        os << std::format("[{},{},{}]", vector.x, vector.y, vector.x );
        return os;
    }
    
    
    int main()
    {
        // C++'s vector which is dynamically resizable array
        // and this is how you can initialize multiple positios 
        // in a few lines of code. 
        std::vector<position_3d_t> positions
        {{
            {1,1,1}, 
            {2,2,2}, 
            {3,3,3}
        }};
    
        // learn about range base for loops 
        // and use them when you don't need indices
        for(const auto& position : positions)
        {
            std::cout << position << "\n";
        }
    }
    
    • -2

相关问题

  • 为什么编译器在这里错过矢量化?

  • 使用带有库的 CMake 编译错误[关闭]

  • 每次我尝试运行预制时都会抛出错误

  • 如何在 C++ 中创建类似于 std::byte 的八位字节类型?

  • C++17 中 std::byte 只能按位运算?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    使用 <font color="#xxx"> 突出显示 html 中的代码

    • 2 个回答
  • Marko Smith

    为什么在传递 {} 时重载解析更喜欢 std::nullptr_t 而不是类?

    • 1 个回答
  • Marko Smith

    您可以使用花括号初始化列表作为(默认)模板参数吗?

    • 2 个回答
  • Marko Smith

    为什么列表推导式在内部创建一个函数?

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 个回答
  • Marko Smith

    为什么 'char -> int' 是提升,而 'char -> Short' 是转换(但不是提升)?

    • 4 个回答
  • Marko Smith

    为什么库中不调用全局变量的构造函数?

    • 1 个回答
  • Marko Smith

    std::common_reference_with 在元组上的行为不一致。哪个是对的?

    • 1 个回答
  • Marko Smith

    C++17 中 std::byte 只能按位运算?

    • 1 个回答
  • Martin Hope
    fbrereto 为什么在传递 {} 时重载解析更喜欢 std::nullptr_t 而不是类? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 您可以使用花括号初始化列表作为(默认)模板参数吗? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi 为什么列表推导式在内部创建一个函数? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A fmt 格式 %H:%M:%S 不带小数 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python C++20 的 std::views::filter 未正确过滤视图 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute 为什么 'char -> int' 是提升,而 'char -> Short' 是转换(但不是提升)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa 为什么库中不调用全局变量的构造函数? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis std::common_reference_with 在元组上的行为不一致。哪个是对的? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev 为什么编译器在这里错过矢量化? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan C++17 中 std::byte 只能按位运算? 2023-08-17 17:13:58 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve