简体   繁体   English

我可以统一初始化模板类的静态const成员吗?

[英]Can I uniformly initialize a static const member of template class?

I have a template class that looks something like this: 我有一个模板类,看起来像这样:

template <typename T>
class foo
{
    static const T arr[16];
};

The contents of foo<T>::arr are numerically identical for all types T that I plan to use. 对于我打算使用的所有类型Tfoo<T>::arr在数值上是相同的。 For example, I would initialize it for T = float and T = double by placing lines in a source file as follows: 例如,我会通过在源文件中放置行来为T = floatT = double初始化它,如下所示:

float foo<float>::arr[16] = {1, 2, 3, 4, ...};
double foo<double>::arr[16] = {1, 2, 3, 4, ...};

Is there a way that I can initialize this in one place without having to repeat myself and enumerate all of the types that T can take on? 有没有办法我可以在一个地方初始化它,而不必重复自己并枚举T可以承担的所有类型? Note that since the type of each array element is T , I can't use the trick of deriving foo<T> from a non-template base class that holds the static array. 请注意,由于每个数组元素的类型都是T ,我不能使用从包含静态数组的非模板基类派生foo<T>的技巧。

What have you tried? 你有什么尝试? This works for me: 这对我有用:

#include <iostream>
using namespace std;

template<typename T>
struct Foo {
    static T const arr[16];
};

template<typename T>
T const Foo<T>::arr[16] = {1,2,3,4};

int main() {
    for ( float const *f = Foo<float>::arr; f != Foo<float>::arr+16; ++f ) {
        cout << *f << " ";
    }
    cout << endl;
    for ( double const *d = Foo<double>::arr; d != Foo<double>::arr+16; ++d ) {
        cout << *d << " ";
    }
    cout << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM