如何在模板类型上使用某些类型特定的函数(例如 std::string 或 std::vector 等的 .size() )?

tho*_*mas 1 c++ template-meta-programming

如果可能,我如何在具有模板类型的函数中使用某些特定于类型的函数(例如.size()for: std::stringor std::vectoror ...),确保当我使用该特定于类型的函数时我实际上正在调用它以正确的类型作为参数?也许我错了,如果是的话,请向我解释我必须做什么。

#include <iostream>
#include <string>

template <typename T>
std::string func(T& number) {
    if (typeid(T) == typeid(std::string)) {
        unsigned short int size = number.size();// !
        return " is a string";
    }
    else if (typeid(T) == typeid(int)) {
        return " is an int";
    }
    //...
}

int main() {
    std::string name = "Anthony";
    int age = 8;
    std::cout << name /*<< func(name) */<< '\n' << age << func(age) << '.';
    return 0;
}

Run Code Online (Sandbox Code Playgroud)

我知道在上面的代码中:

unsigned short int size = number.size();//(I need exactly '.size()')
Run Code Online (Sandbox Code Playgroud)

考虑到我从不使用该值,没有任何意义(即使整个代码也没有多大意义),但找到字符串的大小(当它是字符串时!)正是我所需要的,并且不要发布很长的有意义的代码,我只发布这个代码是为了让它给出我在尝试编译时遇到的错误,并为您提供一个最小的可重现示例。所以请不要对我说“只需删除该行,您的代码就可以工作”)。

Hol*_*Cat 6

而不是if (typeid(T) == typeid(std::string))使用if constexpr (std::is_same_v<T, std::string>). (类似地,else if constexpr代替else if)。

正则if要求两个分支都有效,即使条件在编译时已知。if constexpr需要编译时条件,但允许丢弃的分支无效(仅当错误与模板参数相关时;每个分支在理论上必须对某些模板参数有效)。

std::is_same_v<T, std::string>与 类似typeid(T) == typeid(std::string),只是它被视为编译时常量。if constexpr会拒绝后者。