gpt4 book ai didi

c++ - 模板可变参数和显式实例化

转载 作者:搜寻专家 更新时间:2023-10-31 01:43:36 24 4
gpt4 key购买 nike

我正在尝试同时使用几个新的 C++11 功能。

#include <iostream>
#include <vector>


// Trying out template varargs.
template<typename T, T... args>
struct Test
{
// Using constexpr
// I had assumed that with this I did not need to
// explicitly create an object `values`
// that the compiler will work this out at compile time.
static constexpr T values[] = {args...};
};

// Explicitly instantiate
// the template to force it to generate the appropriate code.
template struct Test<int, 1, 2, 3>;


typedef Test<int, 1, 2, 3> TestInt;

int main()
{
// Silly test to see if it worked.
std::cout << TestInt::values[0] << "\n";
}

这会导致链接器失败。

> g++ -std=c++11 tp.cpp
Undefined symbols for architecture x86_64:
"Test<int, 1, 2, 3>::values", referenced from:
_main in tp-f3440e.o
ld: symbol(s) not found for architecture x86_64

我尝试了几种显式定义 values 数组的变体。但是都没有编译成功。

感谢任何帮助。

更新:

显然这是为@Nikos Athanasiou 编译的,他的例子在这里 http://coliru.stacked-crooked.com/a/474fd3183db003f1

那么这是一个已知的编译器错误吗?

> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix

最佳答案

values 不是仅仅由初始化定义的,而是因为 constexpr 而需要将初始化保留在 Test 中:

template<typename T, T... args> 
constexpr T Test<T, args...>::values[];

参见 here适用于 GCC 4.9 和 Clang 3.4 的完整示例。

#include <iostream>
#include <vector>


// Trying out template varargs.
template<typename T, T... args>
struct Test
{
// Using constexpr
// I had assumed that with this I did not need to
// explicitly create an object `values`
// that the compiler will work this out at compile time.
static constexpr T values[] = {args...};
};

template<typename T, T... args>
constexpr T Test<T, args...>::values[];

// Explicitly instantiate
// the template to force it to generate the appropriate code.
template struct Test<int, 1, 2, 3>;


typedef Test<int, 1, 2, 3> TestInt;

int main()
{
// Silly test to see if it worked.
std::cout << TestInt::values[0] << "\n";
}

关于c++ - 模板可变参数和显式实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24891607/

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