mardi 31 août 2021

Argument type in templated function forced to a given type?

The following runs fine:

#include <iostream>
#include <string>

/**
 * Simply print the value of the argument and adapt the 
 * statement based on its type. 
 */
template<typename T>
int function(T value){

    if(std::is_same<T,double>() || std::is_same<T,float>()){
        std::cout << value << ", type is float" << std::endl; 
        return 0; 
    }
    else if(std::is_same<T,std::string>()){
        std::cout << value << ", type is string" << std::endl; 
        return 0; 
    }
    else if(std::is_same<T,char*>() || std::is_same<T,const char*>()){
        std::cout << value << ", type is char*" << std::endl; 
        return 0; 
    }
    else{
        std::cout << "Unsupported data type" << std::endl; 
        return -1; 
    }
}

int main(){
    function<double>(1.2345); 
    function<std::string>("Hello World");
    const char* sentence = "Hello World"; function<const char*>(sentence);
    return 0; 
}

Since this runs without any issue, I tried changing the following line:

std::cout << value << ", type is string" << std::endl;

to

std::cout << value.c_str() << ", type is string" << std::endl;

However this does not compile. It is like if the type of value was defined when compiling the .c_str() call. However, I would have expected the type of the value argument to only depend on the template argument T. Why isn't it compiling in this case?

Following error is generated:

In instantiation of ‘int function(T) [with T = double]’:
.cpp:321:25:   required from here
error: request for member ‘c_str’ in ‘value’, which is of non-class type ‘double’
   std::cout << value.c_str() << ", type is string" << std::endl;
                ~~~~~~^~~~~
In instantiation of ‘int function(T) [with T = const char*]’:
.cpp:323:70:   required from here
.cpp:306:22: error: request for member ‘c_str’ in ‘value’, which is of non-class type ‘const char*’

Aucun commentaire:

Enregistrer un commentaire