gpt4 book ai didi

c++ - CRTP 中的模板化派生类(奇怪的重复模板模式)

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:13:35 24 4
gpt4 key购买 nike

我使用的 CRTP 不能用 g++ 4.2.1 编译,也许是因为派生类本身就是一个模板?有谁知道为什么这不起作用,或者更好的是,如何让它起作用?示例代码和编译器错误如下。

来源:foo.C

#include <iostream>

using namespace std;

template<typename X, typename D> struct foo;

template<typename X> struct bar : foo<X,bar<X> >
{
X evaluate() { return static_cast<X>( 5.3 ); }
};

template<typename X> struct baz : foo<X,baz<X> >
{
X evaluate() { return static_cast<X>( "elk" ); }
};

template<typename X, typename D> struct foo : D
{
X operator() () { return static_cast<D*>(this)->evaluate(); }
};

template<typename X, typename D>
void print_foo( foo<X,D> xyzzx )
{
cout << "Foo is " << xyzzx() << "\n";
}

int main()
{
bar<double> br;
baz<const char*> bz;

print_foo( br );
print_foo( bz );

return 0;
}

编译器错误

foo.C: In instantiation of ‘foo<double, bar<double> >’:
foo.C:8: instantiated from ‘bar<double>’
foo.C:30: instantiated from here
foo.C:18: error: invalid use of incomplete type ‘struct bar<double>’
foo.C:8: error: declaration of ‘struct bar<double>’
foo.C: In instantiation of ‘foo<const char*, baz<const char*> >’:
foo.C:13: instantiated from ‘baz<const char*>’
foo.C:31: instantiated from here
foo.C:18: error: invalid use of incomplete type ‘struct baz<const char*>’
foo.C:13: error: declaration of ‘struct baz<const char*>’

最佳答案

有一种方法可以让 CRTP 为模板派生类工作,但需要注意的是它应该始终是模板。

#include <iostream>
#include <typeinfo>


template<template <class> class Derived, class T>
struct A{
void interface(){
static_cast<Derived<T>*>(this)->impl();
}
};

template<class T>
struct B: public A<B, T>
{
void impl(){
std::cout << "CRTP with derived templates are real\n";
std::cout << "Tempate argument is " << typeid(T).name() << "\n";
}
};

int main(void)
{
B<char>().interface();
B<double>().interface();
B<void>().interface();
return 0;
}

适用于 gcc 4.4.7 或更早版本,无法确定。

关于c++ - CRTP 中的模板化派生类(奇怪的重复模板模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2940402/

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