gpt4 book ai didi

c++如何初始化部分模板特化的静态变量

转载 作者:可可西里 更新时间:2023-11-01 18:37:07 30 4
gpt4 key购买 nike

我应该如何为偏特化初始化一个静态变量?

template <bool A=true, bool B=false>
struct from {
const static std::string value;
};

// no specialization - works
template <bool A, bool B>
const std::string from<A, B>::value = "";

// partial specialization - does not compile -
// Error: template argument list following class template name must list parameters in the order used in template parameter list
// Error: from<A,B>' : too few template arguments
template <bool B>
const std::string from<true, B>::value = "";

// full specialization - works
const std::string from<false, true>::value = "";

为什么部分不起作用?

编辑:我找到了一个基于 Partial template specialization for initialization of static data members of template classes 的解决方案

在允许我初始化静态变量之前,我需要重复部分特化的声明:

template <bool B>
struct from<true, B> {
const static std::string value;
};

同样,问题是为什么?

最佳答案

如果不对封闭类模板本身进行部分特化,则不允许对成员进行部分特化(无论它们是函数还是静态数据)。

也就是说,您还必须特化类模板。所以以下应该有效:

//partial specialization of class template
template <bool B>
struct from<true, B> {
const static std::string value;
};

//now you can do this!
template <bool B>
const std::string from<true, B>::value = ""

另外,这不会编译(你试过编译这个吗?):

// full specialization - works (SORRY, IT WILL NOT WORK!)
const std::string from<false, true>::value = ""; //this should be an error

你必须这样写:

// full specialization 
template<> //<---- this is important!
const std::string from<false, true>::value = ""

关于c++如何初始化部分模板特化的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13404695/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com