本文介绍了提取C ++模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我对此表示怀疑,但我对是否有可能使用RTTI从现有类型中提取原始类型模板参数感到好奇。

Although I'm doubtful, I'm curious as to whether it's possible to extract primitive-type template parameters from an existing type, perhaps using RTTI.

对于例如:

typedef std::bitset<16> WordSet;

是否可以在上面的代码中提取数字16而无需在其他地方进行硬编码?欢迎编译器特定的实现,尽管我对 g ++ 特别感兴趣。

Would it be possible to extract the number 16 in the above code without hard-coding it elsewhere? Compiler specific implementations are welcome, though I'm particularly interested in g++.

推荐答案

不可能。您通常的操作方式是:

It's not possible. The usual way you do it is this:

template<int N>
struct foo {
    static const int value = N;
};

和类型

template<typename T>
struct foo {
    typedef T type;
};

您可以使用 foo< 39> :: value foo< int> :: type

如果您有特定类型,则可以使用部分模板特化:

If you have a particular type, you can use partial template specialization:

template<typename>
struct steal_it;

template<std::size_t N>
struct steal_it< std::bitset<N> > {
    static const std::size_t value = N;
};

类型参数的确可以使用相同的原理。现在您可以将任何位传递给它,例如 steal_it< std :: bitset< 16> > :: value (请注意使用size_t,而不是int!)。由于我们尚无可变参数的许多模板参数,因此我们必须将自己限制为特定的参数计数,并对数量从1到N的数量重复重复secret_it模板专门化。另一个困难是扫描具有混合参数的类型(类型和非参数类型)。类型参数)。这可能是不容易解决的。

The same principle is possible for type parameters too, indeed. Now you can pass any bitset to it, like steal_it< std::bitset<16> >::value (note to use size_t, not int!). Because we have no variadic many template paramters yet, we have to limit ourself to a particular parameter count, and repeat the steal_it template specializations for count from 1 up to N. Another difficulty is to scan types that have mixed parameters (types and non-types parameters). This is probably nontrivial to solve.

如果没有类型,而只是对象,则可以使用技巧,在编译时仍获得值:

If you have not the type, but only an object of it, you can use a trick, to still get a value at compile time:

template<typename T>
char (& getN(T const &) )[steal_it<T>::value];

int main() {
    std::bitset<16> b;
    sizeof getN(b); // assuming you don't know the type, you can use the object
}

技巧是使函数模板自动推导类型,然后返回对字符数组的引用。该函数不需要定义,唯一需要的就是它的类型。

The trick is to make the function template auto-deduce the type, and then return a reference to a character array. The function doesn't need to be defined, the only thing needed is its type.

这篇关于提取C ++模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:58