template functions, how to send different structures and create a if/else statement based on type?
i'm trying to build a general purpose template function which should function with 2 different type of structure i'll write an example
struct sa {
int a;
int b;
char d;
}
struct sb {
int a;
int b;
int c;
}
template < class T>
void f_print(T & s_passed, bool s_typeB){
std::cout << s_passed.a << endl ;
std::cout << s_passed.b << endl ;
if(s_typeB == false){
std::cout << s_passed.d << endl ;
}else{
std::cout << s_passed.c << endl ;
}
}
then in main:
开发者_运维问答{
struct sa str_TEST_A ;
struct sb str_TEST_B ;
f_print(str_TEST_A,false);
f_print(str_TEST_B,true);
}
now , this is a short example of my issue where i'm handling much more complicated structures, anyway what i get is error: 'struct sa' has no member named 'd'
the problem is that the gnu c++ compiler didn't recognize that not all operations in the function are execute when struct sa is passed, and d is printed only when sb is passed, how i can fix this without creating a duplicated function 1 for each structure type?
thank you :) Francesco
You could move the specialized parts in separate functions and call these from your generic template:
void f_print_special(sa & s_passed) {
std::cout << s_passed.d << endl ;
}
void f_print_special(sb & s_passed) {
std::cout << s_passed.c << endl ;
}
template <class T>
void f_print(T & s_passed) {
std::cout << s_passed.a << endl ;
std::cout << s_passed.b << endl ;
f_print_special(s_passed);
}
sth has the correct answer. However, if you need a more generic solution, in that say the function that accepts sb type could accept any type that implements the concept "has C" (or whatever) then you need to use tag based dispatch. I'd suggest looking it up because though I might be able to describe one hypothetical situation that may or may not resemble your real problem, I couldn't get them all.
It's not just g++. That's invalid C++. Every statement in a function (template or not) must be valid, even if you can "prove" it's not executed.
What's so bad about giving them separate functions? Of course, you can deal with some common subparts by calling another subfunction.
If you want the functions to have the same name, go ahead and do that. Function overloading will handle it.
Perhaps this is just a test case for you in writing templates but a more natural implementation would be to have sa
and sb
inherit from a common base struct sbase
say, with members a
and b
only, and then have sa
and sb
implement their own operator<<
, delegating to the base operator<<
for the common parts.
精彩评论