C++ 具有派生模板类的CRTP未能编译,错误为“0”;“已初始化”;
编辑:正如建议的那样,我将所有问题重新格式化为更简短、更直截了当的问题,如果您需要所有代码,请检查编辑 我试图在.cpp中显式实例化一个CRTP模板,原因有二:C++ 具有派生模板类的CRTP未能编译,错误为“0”;“已初始化”;,c++,c++11,C++,C++11,编辑:正如建议的那样,我将所有问题重新格式化为更简短、更直截了当的问题,如果您需要所有代码,请检查编辑 我试图在.cpp中显式实例化一个CRTP模板,原因有二: 仅启用特定类型的像素(主要是算术) 使用.cpp加快编译时间 但是通过使用以下内容,我对.cpp结尾的显式实例化有问题,下面是代码: 像素.h #include <cstdio> // std::size_t #include <initializer_list> // std
#include <cstdio> // std::size_t
#include <initializer_list> // std::initializer_list
template<typename T, std::size_t N, template<typename> class Derived>
struct Pixel
{
// Friend the derived class to allow it to use current ctor.
friend Derived<T>;
public:
T ch[N];
void print() const;
// Ctor are protected to avoid instantiation of Pixel object
// but they are needed to create the array object at the end.
protected:
Pixel();
Pixel(T val);
Pixel(const std::initializer_list<T>& list);
};
template<typename T>
struct PixRGB : public Pixel<T, 3, PixRGB>
{
// Create an alias for an easy accessor over the base class.
using Base = Pixel<T, 3, PixRGB>;
PixRGB();
PixRGB(T val);
PixRGB(const std::initializer_list<T>& list);
};
但我需要知道typename,比如派生的,以支持如下函数:
template<typename T2>
Derived<T2> convert() const;
模板
派生convert()常量;
您的代码的哪一部分导致了错误?您知道:@super在列表中。当尝试调用:Base(list)
时,会发生此错误,错误显示在call下,但由于main中的调用,列表是输出中的第一个错误。对于piavta,我想在cpp中实现它,首先限制可以使用的类型并加快编译速度。@Vuwox我建议通过删除显示的所有不相关代码页,将此作为一个最小的示例。你会大大增加自己解决问题的机会,也会增加其他人能够帮助你的机会。这已经是一个很小的例子了。我从工作版本中删除了很多函数。但是,我可以尝试通过仅介绍问题而不是旧版本来让它更清晰、更小。您的代码的哪一部分导致了错误?您知道:@super在列表中,当尝试调用:Base(list)
时,会发生此错误,错误出现在调用下,但由于调用main,列表是输出中的第一个错误。对于piavta,我想在cpp中实现它,首先限制可以使用的类型并加快编译速度。@Vuwox我建议通过删除显示的所有不相关代码页,将此作为一个最小的示例。你会大大增加自己解决问题的机会,也会增加其他人能够帮助你的机会。这已经是一个很小的例子了。我从工作版本中删除了很多函数。但是我可以试着通过提出问题而不是旧版本来让它更清晰、更小。
#include <iostream>
#include "Pixel.h"
int main()
{
std::cout << "Sizeof PixRGB<float> : " << sizeof(PixRGB<float>) << std::endl;
PixRGB<float> a = { 1.0f, 2.0f, 3.0f };
a.print();
return 0;
}
Pixel.cpp(42): error C2614: 'PixRGB<float>': illegal member initialization: 'Pixel<float,3,PixRGB<float> >' is not a base or member
Pixel.cpp(42): note: while compiling class template member function 'PixRGB<float>::PixRGB(const std::initializer_list<T> &)'
with
[
T=float
]
Pixel.cpp(45): note: see reference to class template instantiation 'PixRGB<float>' being compiled
Pixel.cpp(41): error C2437: 'Base': has already been initialized
Pixel.cpp(41): note: while compiling class template member function 'PixRGB<float>::PixRGB(T)'
with
[
T=float
]
Pixel.cpp(40): error C2437: 'Base': has already been initialized
Pixel.cpp(40): note: while compiling class template member function 'PixRGB<float>::PixRGB(void)'
template<typename T, std::size_t N, class Derived>
template<typename T2>
Derived<T2> convert() const;