如果传递给函数的参数的数据类型是字符串类型,则抛出异常

Throw exception if the datatype of argument which passed to a function is string type

本文关键字:字符串 类型 抛出异常 参数 函数 如果 数据类型      更新时间:2023-10-16

我有一个方法,可以接收模板类类型的数据类型。在这个函数中,如果参数的数据类型不是字符串类型,我必须做进一步的处理。并且,如果参数是字符串类型,那么我想做异常处理。

template<class K>
class Student
{
private:
    K array[10];
public:
    void assignvalues( K const& index,  const K& val )
    {
        //NOW, I want to check here that the index is not of string type
        array[index] = val;
    }
};
int main()
{
    Student <int> object;
    object.assignvalues(5,9);
    //BUT THIS WILL NOT WORK
    Student <string> object;
    object.assignvalues("Hi","value");
    return 0;
}

使用std::is_same:

if (std::is_same<K, string>::value) {
    // K is string ...
}