2

Is it somehow possible to have callable, non-templated functions in a templated class? Like so:

template<typename T>
class Object
{
public:
  static int loadInfo() { return 0;}
  // more code
};

I'd like to write, e.g.:

Object::loadInfo();

instead of

Object<int8_t>::loadInfo();

It's not virtually important, would just be some 'syntactic sugar'. A bit more background: the function I am thinking of would load some data from disk upon which the program decides which templated version of the object it has to use. ATM it looks like this:

auto usewhat=Object<char>::loadInfo();   // this line feels so wrong
if(usewhat == 0) {
  Object<int8_t> o;
  o.doSomething();
}else if(usewhat == 1){
  Object<int32_t> o;
  o.doSomething();
}else{
  Object<int64_t> o;
  o.doSomething();
}

The only possibilities I can think of atm are 1) using a non-template base class of a different name (say, "BaseObject") or 2) using another class with a different name (say, "InfoObject") ... but both possibilities do not seem too appealing.

BaCh
  • 625
  • 2
  • 5
  • 17

4 Answers4

2

You should make loadInfo a free function (maybe with a different name like loadObjectInfo or whatever makes sense to indicate the semantic relationship with Object).

Even though it is a static function and does not depend on a particular instance of Object, it still depends on Object's template parameters: The function may use T, even though in your case it obviously doesn't. This means that the compiler will generate new code for each Object<T>::loadInfo with different T's, meaning slower builds and potentially larger binaries. Also, you cannot implement the function in a cpp file.

If you have a copy of Scott Meyers' Effective C++ (3rd Edition) available, you might want to look up Item 44 ("Factor parameter-independent code out of templates").

Oberon
  • 3,219
  • 15
  • 30
  • So, the answer to my question is "no." Bummer. Seems this could be a nice addition to the C++ standard. Anyway, selected this answer because of hint to relevant chapter in Meyers' book. Thanks. – BaCh Nov 11 '14 at 15:26
1

Not directly, but you can use a typedef :

typdef Object<int8_t> MyObject;
MyObject::loadInfo();
quantdev
  • 23,517
  • 5
  • 55
  • 88
1

If the function can be moved out of the class, do it.

If it cannot be moved out of the class, but does not depend on T, your class is too fat and should be split.

class ObjectBase {
  // stuff that doesn't depend on T
  static int loadInfo();
};

template <typename T>
class Object : public ObjectBase {
  // more stuff
};
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
0

Actually I suppose there is no portable way of calling functions of template class without specifying template. I also suggest keeping your code portable as much as possible because it will likely help you in the future (with other compiler of with another version of compiler you currently use).

bobrof
  • 1
  • 1