简体   繁体   中英

Template and is_same() doesn't work?

if (std::is_same<T, float>::value)
    {
        float a;
        somefunc_float(x,len,&a);
    }

The above code is from a template, which accept a pointer x that can be a pointer of some primitive data type (eg x being double * , float * or int * ), and somefunc_float is from a lib, can only accept one specific data type of x ( float * in the above example), the compiler always give me error, telling me the input data type (x) is incorrect, as if the expression std::is_same<T, float>::value doest work at all?

The description of the problem is not completely clear, but I think I understand what you are trying to do: You are enclosing a block of code inside the template function with a test that can be performed at compile time, and expect that the compiler will discard that block and not compile it.

Templates don't work like that. When a template is instantiated, the whole template is checked and compiled and the code must be correct before the optimizer can discard blocks of code (which it probably would in this case).

The common approach to obtain that behavior is providing multiple implementations of the template (or non-template overloads) that are called with different types. The compiler will dispatch at the place of call to the appropriate implementation and will then ignore the rest.


There are proposals for static if functionality in a future version of C++ (probably C++17) that would support what you are trying to do.

Now that we have C++17, your approach became valid. However, a minor syntax correction is needed:

// is_same_v is an alias for is_same<...>::value
if constexpr (std::is_same_v<T, float>) {  
    float a;
    somefunc_float(x,len,&a);
}

See the documentation of if for more info.

Types are determined statically , and all template code that is instantiated must compile, ie make sense. The content of an if statement must make sense even if the condition is false.

Try something like this:

template <typename T> execute_if_float(T) { }

execute_if_float(float x) { somefunc_float(x); }


template <typename T> void myCode(T x)
{
    // ...

    execute_if_float(x);

    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM