【问题标题】:How to use Nested static templated structs in c++17如何在 c++17 中使用嵌套的静态模板结构
【发布时间】:2020-12-12 03:03:32
【问题描述】:

我想要实现的是使用一个结构作为另一个结构的模板参数,而不需要实例化,这样这一切都发生在编译时。例如:

template<int v>
struct Container {
    static const int value = v;
};

template<Container a, Container b>
struct BiggerContainer {
    static const int value = a.v > b.v ? a.v : b.v;
};

int main() {
std::cout << BiggerContainer<Container<42>, Container<42>>::value << std::endl;

return 0;
}

我使用此代码得到的错误如下:

./code.cpp: In function 'int main()':
./code.cpp:44:61: error: type/value mismatch at argument 1 in template parameter list for 'template<Container<...auto...> a, Container<...auto...> b> struct BiggerContainer'
   44 |     std::cout << BiggerContainer<Container<42>, Container<42>>::value << std::endl;
      |                                                             ^~
./code.cpp:44:61: note:   expected a constant of type 'Container<...auto...>', got 'Container<42>'
./code.cpp:44:61: error: type/value mismatch at argument 2 in template parameter list for 'template<Container<...auto...> a, Container<...auto...> b> struct BiggerContainer'
./code.cpp:44:61: note:   expected a constant of type 'Container<...auto...>', got 'Container<42>'

我在这里做错了什么?这个错误到底是什么意思我可以改变什么来得到我正在尝试的东西?

谢谢!

【问题讨论】:

    标签: c++ templates struct static constants


    【解决方案1】:

    你可能有:

    template <int v>
    struct Container {
        static const int value = v;
    };
    // template <int v> using Container = std::integral_constant<int, v>;
    
    template <typename lhs, typename rhs>
    struct Max
    {
        static const int value = lhs::value > rhs::value ? lhs::value : rhs::value;
    };
    
    int main() {
        std::cout << Max<Container<42>, Container<42>>::value << std::endl;
    }
    

    【讨论】:

      【解决方案2】:

      在 C++17 中,您不能将类或结构用作非类型模板参数。非类型参数必须是整数、指针、枚举或引用。这在 C++20 中发生了变化。

      具体来说,以下声明将BiggerContainer 参数化为结构的,这是不可能的。

      template<Container a, Container b>
      struct BiggerContainer
      

      代码还有一些其他问题,但这是导致您不得不重新设计的主要问题。

      【讨论】:

        【解决方案3】:

        问题是在BiggerContainer 的模板参数中,您需要为Container 指定模板参数(template&lt;Container, Container&gt; 没有Container 的模板参数)。

        另一种方法是使用模板函数,如下所示:

        template<int v1, int v2>
        int BiggerContainer(Container<v1> a, Container<v2> b)
        {
            return a.value > b.value ? a.value : b.value;
        }
        

        然后这样称呼它:

        BiggerContainer(Container<42>(), Container<42>()); // No need to add '::value'
        

        注意:必须调用构造函数 Container&lt;val&gt;() 而不仅仅是类型 Container&lt;val&gt;。 (因为我们传递的是一个值,而不是一个类型)

        该解决方案的问题在于它返回一个 int(值类型),而不是 Container,但对于某些用途来说可能没问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-06
          • 1970-01-01
          • 2021-10-06
          • 2020-10-29
          • 1970-01-01
          • 2015-12-11
          相关资源
          最近更新 更多