gpt4 book ai didi

c++11 - clang - 如何在头文件中声明一个 static const int?

转载 作者:行者123 更新时间:2023-12-01 11:18:34 29 4
gpt4 key购买 nike

给定头文件中的以下模板,以及一些特化:

template<typename> class A {
static const int value;
};

template<> const int A<int>::value = 1;
template<> const int A<long>::value = 2;

并使用 clang-5 构建,它会导致包含该文件的每个源单元出错,所有单元都提示 A<int>::value 的多个定义。和 A<long>::value .

起初,我认为也许模板特化需要放在特定的翻译单元中,但在检查规范时,这显然应该被允许,因为该值是一个常量整数。

我是不是做错了什么?

编辑:如果我将定义移动到一个翻译单元中,那么我就不能再使用 A<T>::value 的值了。在 const int 的上下文中(例如,它的值用于计算另一个 const 赋值的值),因此该值确实需要在标题中。

最佳答案

在 C++11 中,你也许可以这样做:

template<typename> class B {
public:
static const int value = 1;
};

template<> class B<long> {
public:
static const int value = 2;
};

template<typename T> const int B<T>::value;

如果您只想特化值 var,您可以使用 CRTP。

从 C++17 开始,您可以将定义内联:

template<> inline const int A<int>::value = 1;
template<> inline const int A<long>::value = 2;

同样从 c++17 开始,您可以删除 'template const int B::value;'对于 constexpr:

template<typename> class C {
public:
static constexpr int value = 1;
};

template<> class C<long> {
public:
static constexpr int value = 2;
};

// no need anymore for: template<typename T> const int C<T>::value;

C++11 的另一个解决方案是使用内联方法而不是 C++17 允许的内联变量:

template<typename T> class D { 
public:
static constexpr int GetVal() { return 0; }

static const int value = GetVal();
};

template <> inline constexpr int D<int>::GetVal() { return 1; }
template <> inline constexpr int D<long>::GetVal() { return 2; }

template< typename T>
const int D<T>::value;

除了您上次的编辑:

要在其他依赖定义中也使用您的值,如果您使用内联 constexpr 方法,它似乎是最易读的版本。

编辑:clang 的“特殊”版本,因为正如 OP 告诉我们的那样,clang 提示“实例化后发生特化”。不知道是clang还是gcc那个地方写错了...

template<typename T> class D {
public:
static constexpr int GetVal();
static const int value;
};


template <> inline constexpr int D<int>::GetVal() { return 1; }
template <> inline constexpr int D<long>::GetVal() { return 2; }

template <typename T> const int D<T>::value = D<T>::GetVal();

int main()
{
std::cout << D<int>::value << std::endl;
std::cout << D<long>::value << std::endl;
}

我已经说过,如果不应该重新定义完整的类,CRTP 是可能的。我检查了 clang 上的代码,它编译时没有任何警告或错误,因为 OP 评论说他不明白如何使用它:

template<typename> class E_Impl {
public:
static const int value = 1;
};

template<> class E_Impl<long> {
public:
static const int value = 2;
};

template<typename T> const int E_Impl<T>::value;

template < typename T>
class E : public E_Impl<T>
{
// rest of class definition goes here and must not specialized
// and the values can be used here!

public:

void Check()
{
std::cout << this->value << std::endl;
}
};


int main()
{
E<long>().Check();
std::cout << E<long>::value << std::endl;
E<int>().Check();
std::cout << E<int>::value << std::endl;
}

关于c++11 - clang - 如何在头文件中声明一个 static const int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47069305/

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