使用std :: is_same在if语句中访问类成员 [英] Accessing a class member in an if statement using std::is_same
问题描述
我正在尝试解决以下问题:我想做一个 if
语句,该语句根据模板的参数是否为特定对象以及是否为特定对象来执行某些操作.,调用对象的成员函数.假设我要一个 std :: string
I'm trying to tackle the following problem: I would like to do an if
statement that does something depending on whether the argument of a template is a specific object or not - and if it is, call the object's member function. Let's say I want an std::string
摘要:
#include <iostream>
#include <string>
template <typename T>
void is_string(const T& arg) {
if (std::is_same<T, const std::string&>::value)
std::cout << arg.length() << std::endl;
else
std::cout << "The argument is not a string" << std::endl;
}
int main() {
is_string(0);
return 0;
}
它无法编译,并出现以下错误:
It doesn't compile, with the following error:
types.cpp: In instantiation of ‘void is_string(const T&) [with T = int]’:
types.cpp:13:13: required from here
types.cpp:7:13: error: request for member ‘length’ in ‘arg’, which is of non-class type ‘const int’
std::cout << arg.length() << std::endl;
我认为我要实现的目标在C ++ 11中可能无法实现,但我希望您能提出一些建议,以便能够做到这一点
I reckon that what I'm trying to achieve might not be possible in C++11, but I would appreciate some suggestions on how to be able to do such a thing
推荐答案
在常规 if
语句中,两个分支都必须是有效代码.在您的情况下, int.length()
没有任何意义.
In a regular if
statement, both branches must be valid code. In your case int.length()
makes no sense.
在C ++ 17中,您可以简单地使用 constexpr if
:
In C++17 you could simply use constexpr if
:
if constexpr(std::is_same<T, const std::string&>::value)
std::cout << arg.length() << std::endl;
else
std::cout << "The argument is not a string" << std::endl;
在C ++ 11(或更早版本)中,您可以使用重载来获得类似的结果:
In C++11 (or older) you can employ overloading to achieve similar result:
void foo(std::string const& str){
std::cout << str.length() << std::endl;
}
template<typename T>
void foo(T const&){
std::cout << "The argument is not a string" << std::endl;
}
template <typename T>
void is_string(const T& arg) {
foo(arg);
}
这篇关于使用std :: is_same在if语句中访问类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!