C++ 操作员失踪<&书信电报;但是它';在那里
在这个类中,运算符你的模板有三个参数、一个类型和两个已知最佳匹配类型的常量,但是你的模板化的C++ 操作员失踪<&书信电报;但是它';在那里,c++,templates,C++,Templates,在这个类中,运算符你的模板有三个参数、一个类型和两个已知最佳匹配类型的常量,但是你的模板化的运算符可以用main提供一个示例吗?这是一个令人愉快的模板魔术。你在包装标准的数字类型,不是吗?如果这不是秘密,你的目标是什么?你为什么要这样做?@septgram当然这不是秘密-我的目标是创建安全的int类。我这样做是为了练习模板(meta)programming@DavidRodríguez dribeas当我添加typename时,我收到一个编译器错误,告诉我值/类型不匹配已经“来到镇上”@smal
运算符可以用main提供一个示例吗?这是一个令人愉快的模板魔术。你在包装标准的数字类型,不是吗?如果这不是秘密,你的目标是什么?你为什么要这样做?@septgram当然这不是秘密-我的目标是创建安全的int类。我这样做是为了练习模板(meta)programming@DavidRodríguez dribeas当我添加typename时,我收到一个编译器错误,告诉我值/类型不匹配已经“来到镇上”@smallB:我想我已经回答了你下面的问题,这是问题的一部分。所以你的意思是我应该将它声明为类成员?但是有没有办法将其声明为“独立的”fnc?我已经编辑了答案,您可以做的最简单的事情就是在类范围内定义运算符。或者您可以尝试修复模板。未尝试,因此不保证:template std::ostream&operator不作为成员函数,而是在类范围内作为自由函数声明和定义它。你可以用friend关键字:class X{friend ostream&operator在类范围内定义它。我会试试你的模板,让你知道。我已经编辑了如何在类范围内定义它,你甚至不需要模板部分(我也不希望,在模板中添加一组新的参数将提供不同的语义。
template<class Int_T = int, typename Best_Fit<Int_T>::type Min_Range = std::numeric_limits<Int_T>::min(),
typename Best_Fit<Int_T>::type Max_Range = std::numeric_limits<Int_T>::max()>
class Int
{
Int_T data_;
Int_T get_data()const
{
return data_;
}
};
//Here is this operator defined
template<class Int_T>
std::ostream& operator<<(std::ostream& out, const Int<Int_T, Best_Fit<Int_T>::type, Best_Fit<Int_T>::type>& obj)
{
out << obj.get_data();
return out;
}
#ifndef BEST_FIT_H_INCLUDED
#define BEST_FIT_H_INCLUDED
struct Signed_Type
{
typedef long long type;
};
struct Unsigned_Type
{
typedef unsigned long long type;
};
template<bool Cond, class First, class Second>
struct if_
{
typedef typename First::type type;
};
template<class First, class Second>
struct if_<false,First,Second>
{
typedef typename Second::type type;
};
template<class Int_T>
struct Best_Fit
{//evaluate it lazily ;)
typedef typename if_<std::is_signed<Int_T>::value,Signed_Type,Unsigned_Type>::type type;
};
#endif // BEST_FIT_H_INCLUDED
#include <iostream>
int main(int argc, char* argv[])
{
Int<signed char,1,20> a(30);
cout << a;
}
template<class Int_T = int, typename Best_Fit<Int_T>::type Min_Range
= std::numeric_limits<Int_T>::min(), // constant!
typename Best_Fit<Int_T>::type Max_Range
= std::numeric_limits<Int_T>::max() // constant!
>
class Int
//...
template<class Int_T>
std::ostream& operator<<(std::ostream& out,
const Int<Int_T,
Best_Fit<Int_T>::type, // type!
Best_Fit<Int_T>::type // type!
>& obj)
template<class Int_T = int, typename Best_Fit<Int_T>::type Min_Range
= std::numeric_limits<Int_T>::min(), // constant!
typename Best_Fit<Int_T>::type Max_Range
= std::numeric_limits<Int_T>::max() // constant!
>
class Int {
friend // allows you to define a free function inside the class
std::ostream& operator<<( std::ostream& out,
Int const & obj ) { // Can use plain Int to refer to this
// intantiation. No need to redeclare
// all template arguments
return out << obj.get_data();
}
};